package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zx
 * @date 2021/5/28 22:35
 * @description
 */
public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        // 预处理sql
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, params[0]);
        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        // 封装返回结果集
        ArrayList<Object> resultObjects = getResultObjects(mappedStatement, resultSet);
        return (List<E>) resultObjects;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {
        // 预处理sql
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, params[0]);
        return preparedStatement.executeUpdate();
    }

    /**
     * 返回封装的结果集
     *
     * @param mappedStatement
     * @param resultSet
     * @throws ClassNotFoundException
     * @throws SQLException
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws IntrospectionException
     * @throws InvocationTargetException
     */
    private ArrayList<Object> getResultObjects(MappedStatement mappedStatement, ResultSet resultSet) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, IntrospectionException, InvocationTargetException {
        ArrayList<Object> resultObjects = new ArrayList<>();
        String resultType = mappedStatement.getResultType();
        Class<?> resultclassType = getClassType(resultType);
        while (resultSet.next()) {
            Object o = resultclassType.newInstance();
            // 元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            // 从1开始
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);
                // 反射获获取返回实体和表的关系
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultclassType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            resultObjects.add(o);
        }
        return resultObjects;
    }

    /**
     * 预处理sql
     *
     * @param configuration
     * @param mappedStatement
     * @param param
     * @throws SQLException
     * @throws ClassNotFoundException
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement mappedStatement, Object param) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        // 连接jdbc
        Connection connection = configuration.getDataSource().getConnection();
        // 获取sql语句： 参数未设置 无法识别 jDBC只能识别？占位符
        String sql = mappedStatement.getSql();
        // 转换sql
        BoundSql boundSql = getBoundSql(sql);
        // 获取预处理都西昂
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        // 设置参数
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);
        // 参数为单个参数
        if (Integer.class.equals(parameterTypeClass)) {
            preparedStatement.setObject(1, param);
        } else {
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
            for (int i = 0; i < parameterMappingList.size(); i++) {
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                String content = parameterMapping.getContent();
                // 反射获取
                Field declaredField = parameterTypeClass.getDeclaredField(content);
                // 暴力访问
                declaredField.setAccessible(true);
                Object o = declaredField.get(param);
                preparedStatement.setObject(i + 1, o);
            }
        }
        return preparedStatement;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType != null) {
            Class<?> aclass = Class.forName(paramterType);
            return aclass;
        }
        return null;
    }

    /**
     * 对#{}进行解析 1.代替未？2.进行传值
     */
    private BoundSql getBoundSql(String sql) {
        // 标记处理类 标记解析器对自定义占位符 解释处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        // 解析
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }
}
